<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #video {
      display: block;
      width: 300px;
      height: 400px;
      margin: auto;
      background-color: #333;
      transform: rotateY(180deg);
    }

    #btn {
      margin: 20px auto;
      display: block;
      width: 200px;
      height: 50px;
      line-height: 50px;
      font-size: 18px;
      text-align: center;
      color: #fff;
      background-color: #1752ff;
    }
  </style>
</head>

<body>
  <video id="video" playsinline="playsinline" autoplay="autoplay"></video>
  <div id="btn">切换摄像头</div>
  <script>
    async function getVideoDevices () {
      var devices
      try {
        var devices = await navigator.mediaDevices.enumerateDevices()
      } catch (error) {
        throw error
      }
      if (devices) {
        console.log(devices)
        var videoDevices = devices.filter((device) => {
          return device.kind === 'videoinput'
        })
        return videoDevices
      }
    }
    async function switchCamera () {
      var videoDevices = await getVideoDevices()
      if (window.mediaStream) {
        window.mediaStream.getTracks().forEach(track => track.stop())
      }
      return navigator.mediaDevices.getUserMedia({
        audio: false,
        video: {
          width: 300,
          height: 400,
          deviceId: {
            exact: isFrontCamera ? videoDevices[0].deviceId : videoDevices[videoDevices.length - 1].deviceId
          }
        }
      }).then((mediaStream) => {
        isFrontCamera = !isFrontCamera
        window.mediaStream = mediaStream
        video.srcObject = mediaStream
        video.play()
      }).catch(console.log)
    }
    var video = document.getElementById('video')
    var btn = document.getElementById('btn')
    var isFrontCamera = true
    btn.onclick = function () {
      console.log('切换摄像头')
      switchCamera()
    }
    switchCamera()
  </script>
</body>

</html>